package socket;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;

public class CharServer {

	ServerSocket ss = null;

	List<Client> clients = new ArrayList<Client>();

	public static void main(String[] args) {
		new CharServer().start();
	}

	public void start() {

		try {
			ss = new ServerSocket(8888);
			while (true) {
				Socket s = ss.accept();
				Client c = new Client(s);
				System.out.println("A client Connection!");
				new Thread(c).start();
				clients.add(c);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				ss.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	class Client implements Runnable {

		private DataInputStream dis;

		private DataOutputStream dos;

		public Client(Socket s) {
			try {
				dis = new DataInputStream(s.getInputStream());
				dos = new DataOutputStream(s.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void send(String str) {
			try {
				dos.writeUTF(str);
			} catch (IOException e) {
				clients.remove(this);
				System.out.println("对方退出了！");
			}

		}

		public void run() {
			try {
				while (true) {
					String str = dis.readUTF();
					System.out.println(str);
					for (int i = 0; i < clients.size(); i++) {
						Client c = clients.get(i);
						c.send(str);
					}
				}
			} catch (EOFException e) {
				System.out.println("Connection over!");
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					dis.close();
					dos.close();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
	}
}
